import { ElasticSearchApiService, EsItem } from './services/api.service';
import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil, tap } from 'rxjs/operators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  isLoading = false;
  isTableLoad = false;
  title = 'project';
  list = new Array<EsItem>();
  total = 0;
  keywordList = new Array<string>();
  keyWord = '';
  changeSubject$ = new Subject<string>();
  destroy = new Subject();
  constructor(
    private apiService: ElasticSearchApiService
  ) { }


  ngOnInit(): void {
    this.isTableLoad = true;
    this.apiService.getList('', 1, 10).subscribe(rsp => {
      this.list = rsp.data;
      this.total = rsp.total;
      this.isTableLoad = false;
    });
    this.changeSubject$.pipe(
      debounceTime(500),
      takeUntil(this.destroy),
      tap(_ => {
        this.isLoading = true;
      })
    ).subscribe(k => {
      this.apiService.getKeyWord(k).subscribe(rsp => {
        this.isLoading = false;
        this.keywordList = rsp.keyWordList;
      });
    });
  }
  ngOnDestroy(): void {
    this.destroy.complete();
    this.destroy.unsubscribe();
  }
  // tslint:disable-next-line:typedef
  onSearch() {
    this.isTableLoad = true;
    this.apiService.getList(this.keyWord, 1, 10).subscribe(rsp => {
      this.list = rsp.data;
      this.isTableLoad = false;
    });
  }
  // tslint:disable-next-line:typedef
  onChange(e: string) {
    if (e.length < 1) {
      return;
    }
    this.keyWord = e;
    this.changeSubject$.next(e);
  }
  // tslint:disable-next-line:typedef
  onKeyDow(e: KeyboardEvent) {
    if (e.code === 'Enter') {
      this.onSearch();
    }
  }
}
